#include "Keith.hpp"
#include <cmath>
#include "Main.hpp"
#include "Thread.hpp"
#include <string>
#include <iostream>
#include <stdlib.h>
#include<sstream>
using namespace std;

void FindKeiths(ulong pLimit)
{
	 if (GetVerbose()) cout << "FindKeiths() Begin" << endl;
    for (ulong n = 2L; n <= pLimit; n += 2L) {
        if (IsKeith(n))
            ;
    }
    if (GetVerbose()) cout << "FindKeiths() End" << endl;

}

void *FindKeithsThread(void *pState)
{
	if (GetVerbose()) 
		cout << "FindKeithsThread() Begin" << endl;

    // We know that pState is really a pointer to a ThreadState structure, so type cast it.
    ThreadState *state = static_cast<ThreadState *>(pState);

    // Find all the primes from 2 to state->mLimit.
    FindKeiths(state->mLimit);

    // The thread exit code is 0 (success).
    state->mExitCode = 0;

    // If running verbose mode, then tell the user that the thread is ending.
    if (GetVerbose()) 
		cout << "FindKeithsThread() End" << endl;

    // Exit (terminate) the thread and return pState as the return variable.
    pthread_exit(pState);

}
	
bool IsKeith(ulong pNum)
{
	int n = 3;
	ulong sum = 0;
	ulong  N = pNum;
	
	string initNumber;
	
	std::stringstream strstream;
	
	strstream << pNum;
	strstream >> initNumber;
	
	n = initNumber.length();
	
	ulong variables[n];
	
	for(int i = 0; i<=n; i++)//initializes terms to be added together
	{
		variables[i] = (ulong)initNumber[i];
	}
	
	while(sum < N)
	{
		for(int i = 0; i<=n; i++)//initializes terms to be added together
		{
			sum += variables[i];
		}
		
		for(int i = 0; i<=n; i++)//initializes terms to be added together
		{	if(i!=n)
			{
				variables[i] = variables[i+1];
			}
			else
			{
				variables[i] = sum;
			}
		}
	}
	
	if(sum == N)
	{
		return true;
	}
	
	return false;
}
	
